//src/stores/user.js

import { defineStore } from "pinia";
import { ref ,watch} from "vue";

const STORAGE_KEY = 'user_login_info'

export const useUserStore = defineStore('user',() => {
    const isLoggedIn = ref(false)
    const username = ref('')
    const role = ref('')//'student' or 'teacher'

    //从Local Strorage中回复用户状态
    const loadUser = () =>{
        const storedData = localStorage.getItem(STORAGE_KEY)
        if(storedData){
            const userData = JSON.parse(storedData)
            isLoggedIn.value = userData.isLoggedIn
            username.value = userData.username
            role.value = userData.role
        }
    }

    const login = (user) =>{
        isLoggedIn.value = true
        username.value = user.username
        role.value = user.role

        localStorage.setItem(
            STORAGE_KEY,
            JSON.stringify({isLoggedIn:true,username:user.username,role:user.role})
        )
    };

    const logout =() => {
        isLoggedIn.value = false
        username.value = ''
        role.value = ''
        localStorage.removeItem(STORAGE_KEY)
    };

    watch(
        [isLoggedIn,username,role],
        () => {
            if(isLoggedIn.value){
                localStorage.setItem(
                    STORAGE_KEY,
                    JSON.stringify({isLoggedIn:isLoggedIn.value,username:username.value,role:role.value})
                )
            }
        },
        {deep:true}
    )

    loadUser()
    return {isLoggedIn,username,role,login,logout}
});